package com.zxp.mall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxp.mall.common.to.OrderTo;
import com.zxp.mall.common.utils.PageUtils;
import com.zxp.mall.common.utils.Query;
import com.zxp.mall.common.utils.R;
import com.zxp.mall.common.vo.MemberRespVo;
import com.zxp.mall.order.constant.OrderConstant;
import com.zxp.mall.order.dao.OrderDao;
import com.zxp.mall.order.entity.OrderEntity;
import com.zxp.mall.order.entity.OrderItemEntity;
import com.zxp.mall.order.entity.PaymentInfoEntity;
import com.zxp.mall.order.enume.OrderStatusEnum;
import com.zxp.mall.order.feign.CartFeignService;
import com.zxp.mall.order.feign.MemberFeignService;
import com.zxp.mall.order.feign.ProductFeignService;
import com.zxp.mall.order.feign.WareFeignService;
import com.zxp.mall.order.interceptor.LoginUserInterceptor;
import com.zxp.mall.order.service.OrderItemService;
import com.zxp.mall.order.service.OrderService;
import com.zxp.mall.order.service.PaymentInfoService;
import com.zxp.mall.order.to.orderCreateTo;
import com.zxp.mall.order.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    PaymentInfoService paymentInfoService;

    private ThreadLocal<OrderSubmitVo> submitVoThreadLocal = new ThreadLocal();

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo conformOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberRespVo member = LoginUserInterceptor.threadLocal.get();
        Long memberId = member.getId();

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

//        异步任务丢失上下文 然后给异步任务重新设置上下文内容
        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
//        查询收货地址
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(memberId);
            confirmVo.setAddress(address);
        }, executor);
        CompletableFuture<Void> getUserCartItemsFuture = CompletableFuture.runAsync(() -> {
//        所有选中的购物项
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> userCartItems = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(userCartItems);
        }, executor).thenRunAsync(() -> {
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> skuIds = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R r = wareFeignService.getSkusHasStock(skuIds);
            if (r.getCode() == 0) {
                List<SkuStockVo> data = r.getData(new TypeReference<List<SkuStockVo>>() {
                });
                if (!CollectionUtils.isEmpty(data)) {
                    Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                    confirmVo.setStocks(map);
                }
            }
        }, executor);
//        查询用户积分
        Integer integration = member.getIntegration();
        confirmVo.setIntegration(integration);
        CompletableFuture.allOf(getAddressFuture, getUserCartItemsFuture).get();
//        总额 和 优惠总额自动计算

//        todo: private String orderToken; //防重复令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        confirmVo.setOrderToken(token);
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + member.getId(), token, 30, TimeUnit.MINUTES);

        return confirmVo;
    }

    //    @GlobalTransactional // 高并发场景下不适合使用seata
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        submitVoThreadLocal.set(vo);
        MemberRespVo member = LoginUserInterceptor.threadLocal.get();
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        //1、验证令牌是否合法【令牌的对比和删除必须保证原子性】
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

        //        创建订单 验令牌 验价格 验库存 。。。
        String orderToken = vo.getOrderToken();
//        原子验证令牌和删除锁 0 失败 1 成功
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + member.getId()),
                orderToken);
        if (result == 1L) {
//            1 成功
            responseVo.setCode(0);
            orderCreateTo order = createOrder(); // 订单项
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
//                金额对比成功
//                保存订单
                saveOrder(order);
//                锁定库存 只要有异常就回滚
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> itemVoList = order.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(itemVoList);
                R r = wareFeignService.orderLockStock(lockVo);
                System.out.println("r--->" + r.getCode());
                if (r.getCode() == 0) {
//                    库存锁定成功
                    responseVo.setOrder(order.getOrder());
//                    todo: 发送订单消息到mq
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                    return responseVo;
                } else {
//                    库存锁定失败
                    responseVo.setCode(3);
                    return responseVo;
                }
            } else {
                responseVo.setCode(2);
                return responseVo;
            }
        } else {
//            0 失败
            responseVo.setCode(1);
            return responseVo;
        }

//        String redisToken = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + member.getId());
//        if(StringUtils.isEmpty(redisToken) || !orderToken.equals(redisToken)) {
////            不通过
//            responseVo.setCode();
//        }else{
////            通过
//            redisTemplate.delete(OrderConstant.USER_ORDER_TOKEN_PREFIX + member.getId());
//
//        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity order = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order;
    }

    @Override
    public void closeOrder(OrderEntity entity) {
//        关闭之前要先查询订单的最新状态
        OrderEntity order = this.getById(entity.getId());
        if (order.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()) {
            OrderEntity update = new OrderEntity();
            update.setId(order.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(order, orderTo);

            rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        OrderEntity orderEntity = this.getOrderByOrderSn(orderSn);
        OrderItemEntity order_sn = orderItemService.getOne(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        BigDecimal bigDecimal = orderEntity.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        PayVo payVo = new PayVo();
        payVo.setTotal_amount(bigDecimal.toString());
        payVo.setOut_trade_no(orderSn);
        payVo.setSubject(order_sn.getSkuName());
        payVo.setBody(order_sn.getSkuName());
        return payVo;
    }


    //    保存订单数据
    private void saveOrder(orderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    private orderCreateTo createOrder() {
        orderCreateTo createTo = new orderCreateTo();
//        生成订单号
        String orderSn = IdWorker.getTimeId();
        OrderEntity orderEntity = buildOrderEntity(orderSn);
//        构建订单项
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);

        createTo.setOrderItems(orderItemEntities);
        createTo.setOrder(orderEntity);

//        验价格
        computePrice(orderEntity, orderItemEntities);

        return createTo;
    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
//        订单总额
        BigDecimal total = new BigDecimal("0");
//        优惠金额
        BigDecimal coupon = new BigDecimal("0");
        BigDecimal integration = new BigDecimal("0");
        BigDecimal promotion = new BigDecimal("0");
        Integer giftGrowth = 0;
        Integer giftIntegration = 0;
        for (OrderItemEntity entity : itemEntities) {
            BigDecimal couponAmount = entity.getCouponAmount();
            coupon = coupon.add(couponAmount);
            BigDecimal integrationAmount = entity.getIntegrationAmount();
            integration = integration.add(integrationAmount);
            BigDecimal promotionAmount = entity.getPromotionAmount();
            promotion = promotion.add(promotionAmount);
            total = total.add(entity.getRealAmount());
            giftGrowth = giftGrowth + entity.getGiftGrowth();
            giftIntegration = giftGrowth + entity.getGiftIntegration();
        }
//        设置应付金额
        orderEntity.setTotalAmount(total);
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setCouponAmount(coupon);
        orderEntity.setIntegrationAmount(integration);
//        积分信息
        orderEntity.setGrowth(giftGrowth);
        orderEntity.setIntegration(giftIntegration);
        orderEntity.setDeleteStatus(0); //未删除

    }

    private OrderEntity buildOrderEntity(String orderSn) {
        MemberRespVo memberRespVo = LoginUserInterceptor.threadLocal.get();
        //        获取收货地址
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(memberRespVo.getId());
        OrderSubmitVo orderSubmitVo = submitVoThreadLocal.get();

        R r = wareFeignService.getFare(orderSubmitVo.getAddrId());
        if (r.getCode() == 0) {
            FareVo fareResp = r.getData(new TypeReference<FareVo>() {
            });
            BigDecimal fare = fareResp.getFare();
            MemberAddressVo address = fareResp.getAddress();
//            运费
            orderEntity.setFreightAmount(fare);
//            收货人信息
            orderEntity.setReceiverCity(address.getCity());
            orderEntity.setReceiverDetailAddress(address.getDetailAddress());
            orderEntity.setReceiverName(address.getName());
            orderEntity.setReceiverProvince(address.getProvince());
            orderEntity.setReceiverPhone(address.getPhone());
            orderEntity.setReceiverPostCode(address.getPostCode());
            orderEntity.setReceiverRegion(address.getRegion());

        }
//        订单状态
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        return orderEntity;
    }

    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //        获取所有的订单项
        List<OrderItemVo> userCartItems = cartFeignService.getCurrentUserCartItems();
        if (!CollectionUtils.isEmpty(userCartItems)) {
            List<OrderItemEntity> collect = userCartItems.stream().map(cartItem -> {
                OrderItemEntity orderItem = buildOrderItem(cartItem);
                orderItem.setOrderSn(orderSn);
                return orderItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
//        订单信息
        Long skuId = cartItem.getSkuId();
//        sku信息
        orderItemEntity.setSkuId(skuId);
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPic(cartItem.getImage());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        orderItemEntity.setSkuAttrsVals(StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";"));
        orderItemEntity.setSkuQuantity(cartItem.getCount());

//        spu信息
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        if (r.getCode() == 0) {
            SpuInfoVo spuInfoVo = r.getData(new TypeReference<SpuInfoVo>() {
            });
            orderItemEntity.setSpuId(spuInfoVo.getId());
            orderItemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
            orderItemEntity.setSpuName(spuInfoVo.getSpuName());
            orderItemEntity.setCategoryId(spuInfoVo.getCatalogId());
        }

//        优惠券信息【不做】
//        积分信息
        orderItemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        orderItemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());

//        计算真实价格
        orderItemEntity.setPromotionAmount(new BigDecimal("0.0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0.0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0.0"));
//        实际金额
        BigDecimal orign = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        BigDecimal realAmount = orign.subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(realAmount);

        return orderItemEntity;
    }

//    查询当前登录用户的所有订单
    @Override
    public PageUtils queryPageWithItems(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.threadLocal.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberRespVo.getId()).orderByDesc("id")
        );

        List<OrderEntity> collect = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemEntities);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(collect);

        return new PageUtils(page);
    }

    @Override
    public String handlePayResult(PayAsyncVo vo) {
//        保存交易流水
        PaymentInfoEntity paymentInfo = new PaymentInfoEntity();
        paymentInfo.setAlipayTradeNo(vo.getTrade_no());
        paymentInfo.setOrderSn(vo.getOut_trade_no());
        paymentInfo.setPaymentStatus(vo.getTrade_status());
        paymentInfo.setCallbackTime(vo.getNotify_time());

        paymentInfoService.save(paymentInfo);
        String trade_status = vo.getTrade_status();
        if("TRADE_SUCCESS".equals(trade_status) || "TRADE_FINISHED".equals(trade_status)) {
//            支付成功 修改订单状态
            String outTradeNo = vo.getOut_trade_no();
            baseMapper.updateOrderStatue(outTradeNo, OrderStatusEnum.PAYED.getCode());
        }
        return "success";

    }


}